<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=0.7, minimum-scale=0.2, maximum-scale=1.0, user-scalable=yes"/>
    <title>赛程管理</title>
    <link href="boot.css" rel="stylesheet">
    <script src="common.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }

        h1 {
            margin-bottom: 20px;
            color: #007bff;
        }

        table {
            border-collapse: collapse;
            width: 100%;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        td {
            white-space: pre-line; /* 允许内容换行 */
        }

        /* 按钮样式 */
        .my-button {
            margin-bottom: 20px;
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .my-button:hover {
            background-color: #0056b3;
        }

        /* 弹窗样式 */
        .popup-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 30px; /* 增加 padding 大小 */
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); /* 增加阴影大小 */
            text-align: center;
            z-index: 999; /* 设置 z-index，确保弹窗在最上层 */
            display: none; /* 初始状态隐藏 */
            width: 800px; /* 设置弹窗宽度 */
            height: 350px; /* 设置弹窗高度 */
        }

        .close-button {
            position: absolute;
            top: 10px;
            right: 10px;
            font-size: 20px;
            color: #999;
            cursor: pointer;
        }

        .confirm_decision {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 30px; /* 增加 padding 大小 */
            padding-left: 90px; /* 增加 padding 大小 */
            padding-right: 90px; /* 增加 padding 大小 */
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); /* 增加阴影大小 */
            text-align: center;
            z-index: 999; /* 设置 z-index，确保弹窗在最上层 */
        }

        button {
            padding: 10px 20px;
            font-size: 24px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<div class="confirm_decision" id="confirm_decision" style="display: none;">
    <h2>警告:确认清空所有赛程及记录</h2>
    <button onclick="clearAll()">确认</button>
    <button onclick="cancelConfirmDecision()">取消</button>
</div>
<h1>赛程管理</h1>
<button id="add-row-btn" class="my-button">添加</button>
<button id="download" class="my-button" onclick="downloadAll()">下载所有BP结果</button>
<button id="clear" class="my-button" onclick="confirmDecision()">清空所有赛程</button>
<table id="product-table">
    <thead>
    <tr>
        <th>战队1</th>
        <th>战队2</th>
        <th>状态</th>
        <th>结束时间</th>
        <th>操作</th>
        <th>结果</th>
    </tr>
    </thead>
    <tbody>
    <!-- 这里是动态生成的内容 -->
    </tbody>
</table>
<script>

    if (sessionStorage.getItem("username") === null || sessionStorage.getItem("username") === "undefined") {
        window.location.href = '/bp/login.html'; // 替换为你想要跳转的页面的URL
    }

    function confirmDecision() {
        var block = document.getElementById('confirm_decision')
        block.style.display = 'block';
    }

    function cancelConfirmDecision() {
        var block = document.getElementById('confirm_decision')
        block.style.display = 'none';
    }

    function clearAll() {
        fetch('http://' + ip + ':8080/download', {
            method: 'GET'
        })
            .then(response => {
                return response.blob(); // Convert the response to a Blob
            })
            .then(blob => {
                // Create a temporary link element
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = 'bp结果.xlsx'; // Set the desired file name
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url); // Clean up

                fetch('http://' + ip + ':8080/clear', {
                    method: 'DELETE'
                })
                    .then(() => {
                        // Create a temporary link element
                        if (data.result === "ok") {
                            showAlert('clear successful', 'alert-success');
                        } else {
                            showAlert('clear failed', 'alert-danger');
                        }
                    })
                    .catch(() => {
                        showAlert('clear failed', 'alert-danger');
                    });
                cancelConfirmDecision()
            })
            .catch(error => {
                console.error('Error during download:', error);
            });
    }

    function downloadAll() {
        fetch('http://' + ip + ':8080/download', {
            method: 'GET'
        })
            .then(response => {
                return response.blob(); // Convert the response to a Blob
            })
            .then(blob => {
                // Create a temporary link element
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = 'bp结果.xlsx'; // Set the desired file name
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url); // Clean up
            })
            .catch(error => {
                console.error('Error during download:', error);
            });
    }


    // 构造请求体等代码...

    // 获取添加行按钮
    const addRowBtn = document.getElementById("add-row-btn");

    // 添加行按钮点击事件
    addRowBtn.addEventListener("click", function () {
        // 获取表格的 tbody 元素
        const tableBody = document.querySelector("#product-table tbody");

        // 创建新行元素
        const newRow = document.createElement("tr");
        newRow.contentEditable = true;
        // 创建新单元格元素并添加到新行中
        const cell1 = document.createElement("td");
        cell1.textContent = "test1";
        newRow.appendChild(cell1);

        const cell2 = document.createElement("td");
        cell2.textContent = "test2";
        newRow.appendChild(cell2);

        const cell3 = document.createElement("td");
        cell3.textContent = "";
        newRow.appendChild(cell3);

        const cell4 = document.createElement("td");
        cell4.textContent = "";
        newRow.appendChild(cell4);

        const cell5 = document.createElement("td");
        const confirmButton = document.createElement("button");
        confirmButton.textContent = "确定";
        confirmButton.className = "my-button";
        confirmButton.onclick = confirmUpdate; // 确定按钮点击事件处理函数
        cell5.appendChild(confirmButton);

        const cancelButton = document.createElement("button");
        cancelButton.textContent = "取消";
        cancelButton.className = "my-button";
        cancelButton.onclick = cancelUpdate; // 取消按钮点击事件处理函数
        cell5.appendChild(cancelButton);
        newRow.appendChild(cell5);

        // 将新行添加到表格的 tbody 中的第一行
        tableBody.insertBefore(newRow, tableBody.firstChild);
    });

    function confirmUpdate() {
        const newRow = this.parentNode.parentNode;
        const user1 = newRow.children[0].textContent;
        const user2 = newRow.children[1].textContent;
        // 执行相应的操作，比如发送请求更新数据
        // 这里假设更新操作成功后，恢复原始状态并更新内容
        newRow.contentEditable = false;
        // 更新操作成功后，将表格行的内容恢复为不可编辑状态，并更新为修改后的内容
        update(null, user1, user2);
        location.reload();
    }

    // 取消按钮点击事件处理函数
    function cancelUpdate() {
        const newRow = this.parentNode.parentNode;
        newRow.remove(); // 移除新增的行
    }


    // 构造请求体
    let formData = new FormData();
    let list;
    // 获取表格元素
    const tableBody = document.querySelector("#product-table tbody");
    formData.append('username', sessionStorage.getItem("username"));
    // 发送POST请求
    fetch('http://' + ip + ':8080/schedule', {
        method: 'POST',
        body: formData
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.result === "ok") {
                list = data.data;
// 动态生成表格内容
                list.forEach(schedule => {
                    const row = document.createElement("tr");
                    const user1 = document.createElement("td");
                    user1.textContent = schedule.user1;
                    const user2 = document.createElement("td");
                    user2.textContent = schedule.user2;
                    const status = document.createElement("td");
                    status.textContent = schedule.status;

                    const finishTime = document.createElement("td");
                    finishTime.textContent = schedule.finishTime;

                    const operation = document.createElement("td");
                    const operation1 = document.createElement("td");
                    if (status.textContent !== "已结束") {
                        var button = document.createElement("button");
                        button.textContent = "修改"
                        button.className = "my-button"
                        button.onclick = function () {
                            update1(row, button, operation, schedule);
                        };
                        operation.appendChild(button);
                    }
                    if (status.textContent === "已结束") {
                        var button1 = document.createElement("button");
                        button1.textContent = "查看BP结果"
                        button1.className = "my-button"
                        button1.onclick = function () {
                            showBPResult(schedule.roomId); // 修改这里
                        };
                        operation1.appendChild(button1);
                    }
// 将按钮添加到 operation 元素中
                    row.appendChild(user1);
                    row.appendChild(user2);
                    row.appendChild(status);
                    row.appendChild(finishTime);
                    row.appendChild(operation);
                    row.appendChild(operation1);
                    tableBody.appendChild(row);
                })
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });

    function showBPResult(roomId) {
        // 创建一个隐藏的 <div> 元素
        var popupDiv = document.createElement("div");
        popupDiv.className = "popup-container"; // 添加类名
        popupDiv.id = "popupDiv";

        // 创建关闭按钮
        var closeButton = document.createElement("span");
        closeButton.className = "close-button";
        closeButton.innerHTML = "&times;"; // 使用HTML实体编码表示关闭符号
        closeButton.onclick = function () {
            popupDiv.style.display = "none"; // 点击关闭按钮时隐藏弹窗
        };
        popupDiv.appendChild(closeButton);

        // 创建表格元素
        var table = document.createElement("table");
        table.style.width = "100%";

        // 创建表格内容
        var tbody = document.createElement("tbody");

        const formData = new FormData();
        formData.append('username', sessionStorage.getItem("username"));
        formData.append('roomId', roomId);

        // 发送POST请求
        fetch('http://' + ip + ':8080/record2', {
            method: 'POST',
            body: formData
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.result === "ok") {
                    const products = data.data;

                    // 定义表头标题和表格内容
                    var rows = [
                        ["对阵", products.teamA, "vs", products.teamB],
                        ["第一局", products.firstTeamA, "", products.firstTeamB],
                        ["第二局", products.secondTeamA, "", products.secondTeamB],
                        ["第三局", products.thirdTeamA, "", products.thirdTeamB],
                        ["ban", products.banA, "", products.banB],
                        ["未选", products.unselectedA, "", products.unselectedB],
                        ["BP结束时间", products.endTime, "", ""]
                    ];

                    // 动态生成表格内容
                    rows.forEach(function (row) {
                        var tr = document.createElement("tr");
                        row.forEach(function (cellText, index) {
                            var td = document.createElement("td");
                            td.textContent = cellText;
                            td.style.border = "1px solid black"; // 添加边框
                            td.style.padding = "8px"; // 添加内边距
                            if (index === 0) {
                                td.style.width = "20%"; // 设置第一列宽度
                            } else if (index === 2) {
                                td.style.width = "10%"; // 设置第三列宽度
                            } else {
                                td.style.width = "35%"; // 设置第二和第四列宽度
                            }
                            tr.appendChild(td);
                        });
                        tbody.appendChild(tr);
                    });

                    // 将表格添加到 <div> 中
                    table.appendChild(tbody);
                    popupDiv.appendChild(table);

                    // 将 <div> 添加到页面中
                    document.body.appendChild(popupDiv);

                    // 显示隐藏的 <div>
                    popupDiv.style.display = "block";
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }


    function confirm(row, button, operation, cancelButton, schedule) {
        // 获取修改后的内容
        const user1 = row.children[0].textContent;
        const user2 = row.children[1].textContent;
// 执行相应的操作，比如发送请求更新数据
// 这里假设更新操作成功后，恢复原始状态并更新内容
// 更新操作成功后，将表格行的内容恢复为不可编辑状态，并更新为修改后的内容
        row.contentEditable = false;
        button.textContent = "修改";
        operation.removeChild(cancelButton);
// 更新表格行的内容为修改后的内容
        schedule.user1 = user1;
        schedule.user2 = user2;
        button.onclick = function () {
            update1(row, button, operation, schedule);
        };
        update(schedule.id, user1, user2);
    }

    function update1(row, button, operation, schedule) {
        row.contentEditable = true;
        button.textContent = "确认";
        var cancelButton = document.createElement("button");
        cancelButton.textContent = "取消";
        cancelButton.className = "my-button";
        cancelButton.onclick = function () {
            cancel(row, button, operation, cancelButton, schedule)
        };
        operation.appendChild(cancelButton);
        button.onclick = function () {
            confirm(row, button, operation, cancelButton, schedule);
        };
    }

    function cancel(row, button, operation, cancelButton, schedule) {
        row.contentEditable = false;
        button.textContent = "修改";
        button.onclick = function () {
            update1(row, button, operation, schedule);
        };
        operation.removeChild(cancelButton);
    }

    function update(id, user1, user2) {
        var request = {
            id: id,
            user1: user1,
            user2: user2
        };
        var jsonString = JSON.stringify(request);
        fetch('http://' + ip + ':8080/update/schedule', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: jsonString
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.result === "ok") {

                }
            })
    }

    function showAlert(message, className) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert ${className} mt-4`;
        alertDiv.textContent = message;
        // 居中显示
        alertDiv.style.position = 'fixed';
        alertDiv.style.top = '50%';
        alertDiv.style.left = '50%';
        alertDiv.style.transform = 'translate(-50%, -50%)';

        document.body.appendChild(alertDiv);


        // 3秒后自动关闭弹窗
        setTimeout(() => {
            alertDiv.remove();
        }, 3000);
    }
</script>
</body>
</html>
